const express = require('express')
const Result = require('../../models/Result')
const { decoded } = require('../../utils/index')
const { PRIVATE_KEY, JWT_EXPIRED } = require('../../utils/constant')
const {
  getRoleList,
  getTotalCount,
  editRole,
  createRole,
  deleteRole,
  changePermission,
  allRole
} = require('../../services/role')
const jwt = require('jsonwebtoken')
const qiniu = require('qiniu')
const jwtAuth = require('../jwt')
// 注册路由
const router = express.Router()
router.use(jwtAuth)

// 获取角色列表
router.get('/list', function(req, res, next) {
  const {  pageNum , pageSize  } = req.query
  getRoleList(req.query).then(data => {
    data.forEach(item => {
      item.permissionList = {
        checkedKeys : JSON.parse(item.checkedKeys),
        halfCheckedKeys : JSON.parse(item.halfCheckedKeys)
      }
      delete item.checkedKeys
      delete item.halfCheckedKeys
    })
    getTotalCount(req.query).then(total => {
      new Result({
        list: data,
        page: {
          pageNum,
          pageSize,
          total:total.totalCount
        }
      }, '角色列表查询成功').success(res)
    })
  })
})

//编辑角色接口
router.post('/edit', function(req, res, next) {
  editRole(req.body).then(data => {
    new Result('操作成功').success(res)
  }).catch(err => {
    new Result('操作失败').fail(res)
  })
})

//创建角色接口
router.post('/create', function(req, res, next) {
  createRole(req.body,decoded(req).cardId).then(data => {
    new Result('操作成功').success(res)
  }).catch(err => {
    new Result('操作失败').fail(res)
  })
})

//删除角色接口
router.post('/delete', function(req, res, next) {
  deleteRole(req.body).then(data => {
    new Result('操作成功').success(res)
  }).catch(err => {
    new Result('操作失败').fail(res)
  })
})

router.get('/allList', function(req, res, next) {
  allRole().then(data => {
    new Result(data,'角色列表查询成功').success(res)
  }).catch(err => {
    new Result('操作失败').fail(res)
  })
})

//更新角色权限接口
router.post('/update/permission', function(req, res, next) {
  changePermission(req.body).then(data => {
    new Result('操作成功').success(res)
  }).catch(err => {
    new Result('操作失败').fail(res)
  })
})



module.exports = router